package com.laomuji.android.mvvm.http.encrypt

import com.laomuji.android.mvvm.http.common.CommonUtil
import okhttp3.FormBody
import okhttp3.Request

/**
 * 加密工厂,对body进行加密
 * @author laomuji666
 * @since 2024/2/20
 */
object EncryptFactory {
    object EncryptKey {
        const val ENCRYPT_HEADER_KEY = "ENCRYPT_HEADER_KEY"
        const val BASE64 = "base64"
        const val RSA = "rsa"
    }

    fun encrypt(request: Request, type: String): Request.Builder {
        return when (type) {
            EncryptKey.BASE64 -> wrapEncrypt(request, Base64Encrypt)
            EncryptKey.RSA -> wrapEncrypt(request, RsaEncrypt)
            else -> request.newBuilder()
        }
    }

    private fun wrapEncrypt(request: Request, encryptImpl: BaseEncrypt): Request.Builder {
        val builder = request.newBuilder()
        val body = request.body() ?: return builder
        val mediaType = body.contentType()
        val encryptBody = encryptImpl.encrypt(CommonUtil.getBodyString(request.body()))
        val requestBody = FormBody.create(mediaType, encryptBody)
        return builder.post(requestBody)
    }
}